import { computed, ref } from 'vue';
import loginBg from '@/assets/images/VITE_WDM_THEME-login-bg.png';
import { defineStore } from 'pinia';
import { formatTree, treeToArray, treeToEnum } from '@/utils/utils';
import { fetchDepartmentApi, loginPageConfig } from '@/api/system';
import { COMMON_STORE } from '../constant';

export const useCommonStore = defineStore(
  COMMON_STORE,
  () => {
    const departmentTree = ref<Global.Tree[]>([]);
    const departmentOptions = ref<Global.Option[]>([]);
    const departmentEnum = ref<Record<string, any>>({});
    const fetchDepartment = async () => {
      const res = await fetchDepartmentApi();
      departmentTree.value = formatTree(res.data, { value: 'id' });
      departmentOptions.value = treeToArray(res.data, { value: 'id' });
      departmentEnum.value = treeToEnum(res.data, { value: 'id' });
    };

    const loginBgUrl = ref(loginBg);
    const systemName = ref('');
    const sysName = computed(() => systemName.value || VITE_BASE_TITLE);

    const fetchSysConfig = () => {
      loginPageConfig().then((res) => {
        const { loginImgUrl, systemName: _systemName } = res.data as any;
        loginBgUrl.value = loginImgUrl;
        systemName.value = _systemName;
      });
    };

    // onMounted(() => {
    //   fetchSysConfig();
    // });

    return {
      fetchDepartment,
      departmentTree,
      departmentOptions,
      departmentEnum,
      sysName,
      loginBgUrl,
      fetchSysConfig,
    };
  },
  {
    persist: true,
  },
);
